<template>
  <div>
    <Col :lg="24" :md="16">
    <Card class="warp-card" dis-hover>
      <Row justify="space-between" type="flex">
        <Col>
          <Input
            placeholder="电芯类型编码"
            style="width: 200px;"
            v-model="searchForm.code"
          />
          <Button
            @click="searchData" icon="md-search"
            style="margin-left: 20px;"
            type="primary"
            v-privilege="'search-electricFactory'"
          >查询
          </Button>
          <Button
            @click="clearSearch"
            style="margin-left: 20px;"
            icon="md-refresh"
            type="default"
            v-privilege="'search-electricFactory'"
          >重置
          </Button>
        </Col>
        <Col>
          <Button
            @click="isShowAddModal=true"
            icon="md-add"
            type="primary"
            v-privilege="'add-electricFactory'"
          >新建
          </Button>
        </Col>
      </Row>
      <!-- Form 搜索按钮区 end -->
      <Row style="padding-top:10px; ">
        <Col :lg="24" :md="24">
          <Table :columns="columns" :data="data" :loading="isShowTablesLoading" ref="tablesMain"></Table>
        </Col>
      </Row>
      <Row class="page" justify="end" style="position: relative;margin-top: 10px;" type="flex">
        <Page
          :current="searchForm.pageNum"
          :page-size="searchForm.pageSize"
          :total="totalPage"
          @on-change="changePage"
          show-total
          show-elevator
        ></Page>
      </Row>
    </Card>
    <!-- Card 内容区 end -->
    <Modal
      :loading="isShowUpdateLoading"
      :closable="false"
      title="编辑电芯类型"
      width="740"
      v-model="isShowEditModal"
    >
      <Form :label-width="100" :model="updateItem" :rules="updateValidate" ref="updateRef">
        <FormItem label="电芯类型编码" prop="code">
          <Input :maxlength="50" placeholder="请输入电芯类型编码(必填)" v-model="updateItem.code"></Input>
        </FormItem>
        <FormItem label="电芯类型名称" prop="type">
          <Input :maxlength="30" placeholder="请输入电芯类型名称(必填)" v-model="updateItem.type"
                  @on-keydown="updateItem.type=updateItem.type.replace(/^ +| +$/g,'')"
                  @on-keyup="updateItem.type=updateItem.type.replace(/^ +| +$/g,'')"
          ></Input>
        </FormItem>
        <FormItem label="描述" prop="remark">
          <Input
            :autosize="{minRows: 5, maxRows: 8 }"
            :maxlength="maxlength"
            @input="descInput"
            placeholder="请输入描述"
            type="textarea"
            v-model="updateItem.remark "
          ></Input>
          <span class="text">{{ remnant }}/{{maxlength}}</span>
        </FormItem>
      </Form>
       <div slot="footer">
        <Button
          @click="cancelUpdateData"
        >取消</Button>
        <Button
          type="primary"
          @click="validateAndupdateelectricFactoryConfig"
        >确定</Button>
    </div>
    </Modal>
    <Modal
      :loading="isShowSaveLoading"
      title="新建电芯类型"
      :closable="false"
      width="740"
      v-model="isShowAddModal"
    >
      <Form :label-width="100" :model="saveItem" :rules="saveValidate" ref="saveRef">
        <FormItem label="电芯类型编码" prop="code">
          <Input :maxlength="50" placeholder="请输入电芯类型编码(必填)" v-model="saveItem.code"></Input>
        </FormItem>
        <FormItem label="电芯类型名称" prop="type">
          <Input :maxlength="30" placeholder="请输入电芯类型名称(必填)" v-model="saveItem.type"
                  @on-keydown="saveItem.type=saveItem.type.replace(/^ +| +$/g,'')"
                  @on-keyup="saveItem.type=saveItem.type.replace(/^ +| +$/g,'')"
          ></Input>
        </FormItem>
        <FormItem label="描述" prop="remark">
          <Input
            :autosize="{minRows: 5, maxRows: 8 }"
            :maxlength="maxlength"
            @input="descInput"
            placeholder="请输入描述"
            type="textarea"
            v-model="saveItem.remark "
          ></Input>
          <span class="text">{{ remnant }}/{{maxlength}}</span>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button
          @click="cancelSaveData"
        >取消</Button>
        <Button
          type="primary"
          @click="validateAndaddelectricFactoryConfig"
        >确定</Button>
    </div>
    </Modal>
    </Col>
  </div>
</template>

<script>
import { electricTypeConfigApi } from '@/api/electric-type-config';
import { validateTextLength} from '@/lib/util';
export default {
  name: 'electricFactoryConfigManage',
  components: {},
  props: {},
  data() {
    return {
      isShowPage: true,
      searchValue: '',
      remnant: 100,
      maxlength:100,
      isShowEditModal: false,
      isShowAddModal: false,
      // table是否Loading
      isShowTablesLoading: true,
      isShowSaveLoading: true,
      isShowUpdateLoading: true,
      totalPage: 0,
      // 更新的数据
      updateItem: {
        id:'',
        code: '',
        type:'',
        configType:3,
        remark:''
      },
      // 添加保存的数据
      saveItem: {
        code: '',
        type:'',
        remark:'',
        configType: 2,
      },
      saveItemInt: {},
      // table表头
      columns: [
        {
          title: '序号',
          width: 60,
          type:"index"
        },
        {
          title: '电芯类型编码',
          key: 'code'
        },
        {
          title: '电芯类型名称',
          key: 'type'
        },
        {
          title: '描述',
          key: 'remark'
        },
        {
          title: '创建人',
          key: 'createByName',
          width: 120
        },
        {
          key: 'createTime',
          width: 160,
          title: '创建时间',
          align: 'left'
        },
        {
          key: 'updateTime',
          width: 160,
          title: '更新时间',
          align: 'left'
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
          className: 'action-hide',
          render: (h, params) => {
            return this.$tableAction(h, [
              {
                title: '编辑',
                directives: [
                  {
                    name: 'privilege',
                    value: 'update-electricFactory'
                  }
                ],
                action: () => {
                  this.updateItem={
                    id:params.row.id,
                    code:params.row.code,
                    type:params.row.type,
                    remark:params.row.remark
                  }
                  this.isShowEditModal = true
                }
              },
              {
                title: '删除',
                directives: [
                  {
                    name: 'privilege',
                    value: 'delete-electricFactory'
                  }
                ],
                action: () => {
                  this.$Modal.confirm({
                    title: '友情提醒',
                    content: '确定要删除吗？',
                    onOk: () => {
                      this.deleteelectricFactoryConfigById(params.row.id);
                    }
                  });
                }
              }
            ]);
          }
        }
      ],
      // table数据
      data: [],
      updateValidate: {
        code: [
          { required: true, message: '请输入电芯类型编码', trigger: 'blur' }
        ],type: [
          { required: true, message: '请输入电芯类型名称', trigger: 'blur' }
        ]
      },
      saveValidate: {
       code: [
          { required: true, message: '请输入电芯类型编码', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请输入电芯类型名称', trigger: 'blur' }
        ]
      },
      searchForm: {
        code: '',
        pageNum: 1,
        pageSize: 10,
        configType: 2,
        searchCount: true,
        sort: false
      },
      searchFormInt: {},
      isShowdeleteLoading: false
    };
  },
  computed: {},
  watch: {
    isShowAddModal(val) {
      if (val) {
        this.remnant = 0;
      }
    },
  },
  filters: {},
  created() {},
  mounted() {
    Object.assign(this.searchFormInt, this.searchForm);
    Object.assign(this.saveItemInt, this.saveItem);
    this.getelectricFactoryConfigListPage();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  methods: {
    // 分页查询任务节点
    async getelectricFactoryConfigListPage() {
      try {
        this.isShowTablesLoading = true;
        this.isShowPage = true;
        let result = await electricTypeConfigApi.getElectricConfigByPage(this.searchForm);
        this.isShowTablesLoading = false;
        let datas = result.data;
        this.data = datas.list;
        this.totalPage = datas.total;
      } catch (e) {
        this.isShowTablesLoading = false;
        console.error(e);
      }
    },
    // 页码改变
    changePage(pageNum) {
      this.searchForm.pageNum = pageNum;
      this.getelectricFactoryConfigListPage();
    },
    //打开新页面
    showSelectModal(){
      this.$refs.electricFactorySelect.showModal();
    },
    // 改变每页显示数据条数
    changePageSize(pageSize) {
      this.searchForm.pageNum = 1;
      this.searchForm.pageSize = pageSize;
      this.getelectricFactoryConfigListPage();
    },
    descInput() {
      let remark = this.updateItem.id?this.updateItem.remark:this.saveItem.remark;
      let txtVal = validateTextLength(remark);
      this.remnant = this.maxlength - txtVal;
    },
    // 检验参数后 更新节点
    validateAndupdateelectricFactoryConfig() {
      this.$refs['updateRef'].validate(valid => {
        this.isShowUpdateLoading = true;
        if (valid) {
          this.updateelectricFactoryConfig();
        } else {
          this.isShowUpdateLoading = false;
          this.$nextTick(() => {
            this.isShowUpdateLoading = true;
          });
        }
      });
    },
    // 更新配置
    async updateelectricFactoryConfig() {
      try {
        this.updateItem.configType = 2
        let result = await electricTypeConfigApi.updateElectricConfig(this.updateItem);
        this.$Message.success('修改成功');
        this.$emit('updateSuccess');
        await this.getelectricFactoryConfigListPage();
        this.cancelUpdateData();
      } catch (e) {
        this.isShowUpdateLoading = false;
        this.$nextTick(() => {
          this.isShowUpdateLoading = true;
        });
        //TODO zhuoda sentry
        console.error(e);
      } finally {
        this.isShowUpdateLoading = false;
      }
    },
    // 清除编辑模态框数据
    cancelUpdateData() {
      this.updateItem = {};
      // 清空form规则检查
      this.$refs['updateRef'].resetFields();
      this.isShowEditModal = false;
    },
    // 搜索
    searchData() {
      this.pageNum = 1;
      this.getelectricFactoryConfigListPage();
    },
    // 重置
    clearSearch() {
      Object.assign(this.searchForm, this.searchFormInt);
      this.getelectricFactoryConfigListPage();
    },
    validateAndaddelectricFactoryConfig() {
      try {
        this.$refs['saveRef'].validate(valid => {
          this.isShowSaveLoading = true;
          if (valid) {
            this.addelectricFactoryConfig();
          } else {
            this.isShowSaveLoading = false;
            this.$nextTick(() => {
              this.isShowSaveLoading = true;
            });
          }
        });
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
      }
    },
    // 新增节点 - 异步
    async addelectricFactoryConfig() {
      try {
        let result = await electricTypeConfigApi.addElectricConfig(this.saveItem);
        this.$Message.success('添加成功');
        this.$emit('addSuccess');
        this.isShowSaveLoading = true;
        await this.getelectricFactoryConfigListPage();
        this.cancelSaveData();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowSaveLoading = false;
      }
    },
    // 清除添加模态框数据
    cancelSaveData() {
      Object.assign(this.saveItem, this.saveItemInt);
      // 清空form规则检查
      this.$refs['saveRef'].resetFields();
      this.isShowAddModal = false;
    },
    // 根据ID删除节点
    async deleteelectricFactoryConfigById(id) {
      try {
        this.isShowdeleteLoading = true;
        let result = await electricTypeConfigApi.deleteElectricConfig(id);
        this.isShowdeleteLoading = false;
        this.$Message.success('删除成功');
        await this.getelectricFactoryConfigListPage();
        this.cancelSaveData();
      } catch (e) {
        //TODO zhuoda sentry
        console.error(e);
        this.isShowdeleteLoading = false;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.text{
    position: absolute;
    right: 10px;
    bottom: -5px;
}
</style>
